<?php
class User extends CActiveRecord {
    
    public $userid;
    public $groupId;
    public $login;
    public $email;
    public $password;
    public $regDate;
    public $logDate;
    public $weight = 1;
    public $twitter;
    public $site;
    public $skype;
    public $descr;
    public $avatar;
    public $unblockDate;
    public $isBanned;
    public $role=0;
    public $displayName;
    
    public $newPassword;
    private $oldRole;
    
    // on=>reg :
    public $validacion;
    public $subscr = false;
    public $workPartners;
    
    //for loginza :
    public $u_provider;
    public $u_identity;
    
    //for moder role:
    public $cats;
    public $partners;
    
    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    public function tableName() {
        return 'users';
    }
    
    public function attributeLabels() {
        return array(
            'site' => 'Сайт',
            'twitter' => 'Профиль в твиттере',
            'skype' => 'Skype', 
            'login' => 'Логин',
            'displayName' => 'Псевдоним',
            'email' => 'Email',
            'descr' => 'О себе',
            'newPassword' => 'Новый пароль',
            'validacion' => 'Капча',
            'groupId' => 'Полномочия',
            'regDate' => 'Дата регистрации',
            'password' => 'Пароль',
            'subscr' => 'Подписаться',
            'avatar' => 'Аватар',
            'isBanned' => 'Заблокировать пользователя',
            'unblockDate' => 'Заблокировать на несколько дней:',
            'role'=>'Стандартные полномочия'
        );
    }
  
    public function rules() {
        return array(
            array('login, email', 'required', 'message'=>'{attribute} обязателен для заполнения'),
            array('email', 'email', 'message'=>'В поле email есть ошибка'),
            array('email, skype, login', 'unique'),
            array('newPassword', 'length', 'min'=>'6', 'max'=>'12', 'tooShort'=>'Пароль должен содержать минимум 6 знаков', 'tooLong'=>'Максмальная длина пароля 12 знаков', 'allowEmpty'=>true),
            array('site', 'url', 'message' => 'Ошибка в URL адресе {attribute}'),
            array('groupId, role, descr, subscr, isBanned, regDate, weight, workPartners, partners, cats, onlyCats', 'safe'),
            array('unblockDate', 'numerical', 'allowEmpty' => true, 'integerOnly' => true),
            array('displayName', 'length', 'min'=>'3', 'max'=>'32', 'tooShort'=>'Псевдоним должен содержать минимум 3 знака', 'tooLong'=>'Максмальная длина пседонима 32 знака', 'allowEmpty'=>true),
            array('displayName', 'displayNameValidator'),
            array('login', 'match', 'pattern' => '/^[a-zA-Z]{1}(.+){1,}$/', 'message' => '{attribute} введен не правильно'),
            array('login', 'length', 'encoding'=>'utf-8', 'max'=>30, 'min'=>3, 'tooShort'=>"Логин слишком короткий", 'tooLong'=>"Логин слишком длинный"),
            array('password', 'length', 'min'=>'6', 'max'=>'32', 'tooShort'=>'Пароль должен содержать минимум 6 знаков', 'tooLong'=>'Максмальная длина пароля 12 знаков', 'on'=>'insert'),
            array('twitter, site', 'length', 'encoding'=>'utf-8', 'max'=>128, 'min'=>3, 'tooShort'=>"{attribute} слишком короткий", 'tooLong'=>"{attribute} слишком длинный"),
            array('avatar', 'file', 'types'=>'png, jpg, gif', 'maxSize'=>100000, 'allowEmpty'=>true, 'on'=>'uploadAvatar'),
            
            array('skype, login, site, twitter, descr', 'filter', 'filter'=>'strip_tags'),
            
            array('validacion', 'application.extensions.recaptcha.EReCaptchaValidator', 'privateKey'=>'6Le74uQSAAAAAMlk_Mb2U1BGd-5G0Jh1FzQMXoNc ', 'message'=>'Слова на капче введены не правильно', 'on'=>'reg'),
        );
    }
    
    public function displayNameValidator() {
        if($this->getIsNewRecord())
            $check = Yii::app()->db->createCommand('select 1 from users where displayName="'.$this->displayName.'" or login="'.$this->displayName.'"')->queryRow();
        else $check = Yii::app()->db->createCommand('select 1 from users where (displayName="'.$this->displayName.'" or login="'.$this->displayName.'") and userId<>'.$this->primaryKey)->queryRow();
        if($check) $this->addError ('displayName', 'Псевдоним уже занят другим');
    }
    
    public function relations() {
        return array(
            'group'=>array(self::BELONGS_TO, 'Group', 'groupId'),
        );
    }
        
    public function beforeSave() {
        if(!parent::beforeSave()) return false;
        if(empty($this->displayName)) $this->displayName = $this->login;
        if($this->getIsNewRecord()) {
            $this->regDate = time();
            $this->password = !empty($this->password) ? md5($this->password) : md5(time().'*&4');
        } else {
            if($this->unblockDate) 
                $this->unblockDate = time () + $this->unblockDate * 86400; 
        }
        if($this->newPassword) {
            $this->password = md5($this->newPassword);
        }
        $this->assignRole();
        return true;
    }

    private function assignRole() {
        if($this->role) {
            $this->groupId = 0;
            if($this->role == 'moder') {
                Yii::app()->db->createCommand()->delete('forum_moderator', 'userId='.$this->userid);
                if(!empty($this->cats)) {
                    if(!empty($this->partners)) {
                        $cats = $this->cats;
                        for($i=0; $i<count($this->cats); $i++) {
                            for($l=0; $l<count($this->partners); $l++) {
                                $data = split(',', $this->partners[$l]);
                                if($data[1] == $this->cats[$i]) {
                                    Yii::app()->db->createCommand()->insert('forum_moderator', array('partnerId'=>$data[0], 'catId'=>$this->cats[$i], 'userId'=>$this->getPrimaryKey()) );
                                    unset($cats[$i]);
                                }
                            }
                        }
                        foreach ($cats as $c) 
                            Yii::app()->db->createCommand()->insert('forum_moderator', array('catId'=>$c, 'userId'=>$this->getPrimaryKey() ));
                    } else {
                        for ($i = 0; $i<count($this->cats); $i++) 
                            Yii::app()->db->createCommand()->insert('forum_moderator', array('catId'=>$this->cats[$i], 'userId'=>$this->getPrimaryKey() ));
                    }
                }
            } 
        } else $this->role = 'user';
    }
    
    public function beforeDelete() {
        if(!parent::beforeDelete()) return false;
        if(!empty($this->avatar) && file_exists(Yii::getPathOfAlias('webroot').'/images/userAvatars/'.$this->avatar)) {
            unlink(Yii::getPathOfAlias('webroot').'/images/userAvatars/'.$this->avatar);
        }
        return true;
    }
    
    protected function afterFind() {
        if(!parent::afterFind()) return false;
        $this->oldRole = $this->role;
        return true;
    }

    protected function afterSave() {
        if(!$this->getIsNewRecord()) {
            Yii::app()->user->setState('site', $this->site);
            Yii::app()->user->setState('avatar', $this->avatar);
            Yii::app()->user->setState('descr', $this->descr);
            Yii::app()->user->setState('email', $this->email);
            Yii::app()->user->setState('skype', $this->skype);
        }
        if(!empty($this->workPartners)) {
            $workPartnersId = split(',', $this->workPartners);
            for($i=0; $i<count($workPartnersId); $i++) {
                if(!empty($workPartnersId[$i]) && Partner::model()->exists('partnerid='.$workPartnersId[$i])) 
                    Yii::app()->db->createCommand()->insert('partners_users', array('userId'=>$this->userid, 'partnerId'=>$workPartnersId[$i]));
            }
        }
        if($this->getIsNewRecord()) {
            Yii::app()->db->createCommand()->update('subscribers', array('userId'=>$this->userid), '`email`="'.$this->email.'"');
        }
        if(!empty($this->subscr)) 
            Yii::app()->db->createCommand()->insert('subscribers', array('type'=>'partner', 'email'=>$this->email, 'userId'=>$this->userid));
    }
}